<template>
  <div class="app-container">
    <div
      v-show="
        !exportInfo.visible &&
        !detailInfo.visible &&
        !purchOrderIndfo.visible &&
        !applicationOrderInfo.visible &&
        !purchOrderDetailInfo.visible &&
        !applicationOrderDetailsInfo.visible &&
        !downShelfTaskInfo.visible &&
        !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slipSelectRequest="slipSelectRequest"
          :clearType="clearType"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-audit>
            <el-button :disabled="!canAudit" @click="audit()">批准</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :check-box="true"
        :tab-index="true"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>

        <template v-slot:col-useOrderNo="scope">
          <span>{{ scope.row.useApplication.orderNo }}</span>
        </template>
        <template v-slot:col-sumQty="scope">
          <p>{{ $fn.qtyFormatter(scope.row.sumStorageQty) }}</p>
          <p>{{ $fn.qtyFormatter(scope.row.sumQty) }}</p>
        </template>
        <template v-slot:col-purchOrder="scope">
          <!--转采-->
          <div v-if="scope.row.turnOrders && scope.row.turnOrders.length > 0">
            <div v-if="$permission('purchOrder:detail')">
              <span v-for="(item, index) in scope.row.turnOrders" :key="index"
                ><span
                  class="slip-edit"
                  @click="showPurchOrderDetail(item.id, scope.row)"
                  >{{ item.orderNo || '-' }}</span
                ><span
                  v-if="
                    scope.row.turnOrders.length > 0 &&
                    scope.row.turnOrders.length - 1 !== index
                  "
                  >,</span
                ></span
              >
            </div>
            <div v-else>
              <span v-for="(item, index) in scope.row.turnOrders" :key="index"
                >{{ item.orderNo || ''
                }}<span
                  v-if="
                    scope.row.turnOrders.length > 0 &&
                    scope.row.turnOrders.length - 1 !== index
                  "
                  >,</span
                ></span
              >
            </div>
          </div>
          <div v-else>-</div>
          <!--转申-->
          <div
            v-if="
              scope.row.turnApplications &&
              scope.row.turnApplications.length > 0
            "
          >
            <div v-if="$permission('purchApplication:detail')">
              <span
                v-for="(item, index) in scope.row.turnApplications"
                :key="index"
                ><span
                  class="slip-edit"
                  @click="showApplicationOrderDetail(item.id, scope.row)"
                  >{{ item.orderNo }}</span
                ><span
                  v-if="
                    scope.row.turnApplications.length > 0 &&
                    scope.row.turnApplications.length - 1 !== index
                  "
                  >,</span
                ></span
              >
            </div>
            <div v-else>
              <span
                v-for="(item, index) in scope.row.turnApplications"
                :key="index"
                >{{ item.orderNo || ''
                }}<span
                  v-if="
                    scope.row.turnApplications.length > 0 &&
                    scope.row.turnApplications.length - 1 !== index
                  "
                  >,</span
                ></span
              >
            </div>
          </div>
          <div v-else>-</div>
        </template>
      </TableContainer>
    </div>
    <!-- 明细 -->
    <audit-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      :id="detailInfo.id"
      :tableRow="detailInfo.tableRow"
      @returnBack="getList"
    />
    <export
      v-if="exportInfo.visible"
      v-model:visible="exportInfo.visible"
      :title="exportInfo.title"
      :id="exportInfo.id"
      @returnModify="getList"
    />
    <DownShelfTask
      v-if="downShelfTaskInfo.visible"
      v-model:visible="downShelfTaskInfo.visible"
      :title="downShelfTaskInfo.title"
      :id="downShelfTaskInfo.id"
      @returnModify="getList"
    />
    <purch-order
      v-if="purchOrderIndfo.visible"
      v-model:visible="purchOrderIndfo.visible"
      :tableRow="purchOrderIndfo.tableRow"
      @returnBack="getList"
    />
    <application-order
      v-if="applicationOrderInfo.visible"
      v-model:visible="applicationOrderInfo.visible"
      :tableRow="applicationOrderInfo.tableRow"
      @returnBack="getList"
    />
    <purch-order-detail
      v-if="purchOrderDetailInfo.visible"
      v-model:visible="purchOrderDetailInfo.visible"
      :purchOrderId="purchOrderDetailInfo.purchOrderId"
      @returnBack="getList"
    />
    <purch-application-detail
      v-if="applicationOrderDetailsInfo.visible"
      v-model:visible="applicationOrderDetailsInfo.visible"
      :tableRow="applicationOrderDetailsInfo.data"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="useAudit">
import {
  getUseApplicationCustomizeList,
  auditUseApplication,
  validateDepotHighLevel,
  rejectUseApplication,
  applicationsCancel,
  stopUseApplication,
} from '@/api/use.js'
const AuditDetail = defineAsyncComponent(() => import('./details'))
const Export = defineAsyncComponent(() => import('./export'))
const DownShelfTask = defineAsyncComponent(() => import('./downShelfTask'))
const PurchOrder = defineAsyncComponent(() => import('./purch'))
const ApplicationOrder = defineAsyncComponent(() => import('./application'))
const PurchOrderDetail = defineAsyncComponent(() =>
  import('@/views/purch/order/detail')
)
const PurchApplicationDetail = defineAsyncComponent(() =>
  import('@/views/purch/application/detail')
)
const detailList = defineAsyncComponent(() => import('./detailList'))
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

import { validateDownShelf } from '@/api/use'
const { proxy } = getCurrentInstance()
// 过滤相关配置

const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {},
    customizeUserVO: {},
    queryParams: {
      status: [2, 4, 7, 9, 10],
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'audit',
      show: proxy.$permission('useAudit:audit'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '生成出库单',
        event: _export,
        show: proxy.$permission('useAudit:export'),
        ifRender(row) {
          return row.status === 4 || row.status === 7
        },
      },
      // {
      //   label: '生成wms出库单',
      //   event: downShelfTask,
      //   show: proxy.$permission('useAudit:downShelfTask'),
      //   ifRender(row) {
      //     return (
      //       (row.status === 4 || row.status === 7) &&
      //       row.isCargoSpaceManage == 1
      //     )
      //   },
      // },
      // {
      //   label: "转为采购单",
      //   event: auditPurch,
      //   show: true,
      //   ifRender(row) {
      //     return (
      //       row.status === 2 ||
      //       row.status === "part_export" ||
      //       row.status === "part_turn"
      //     );
      //   }
      // },
      // {
      //   label: "转为申购单",
      //   event: auditApplication,
      //   show: true,
      //   ifRender(row) {
      //     return (
      //       row.status === 2 ||
      //       row.status === "part_export" ||
      //       row.status === "part_turn"
      //     );
      //   }
      // },
      // {
      //   label: "取消",
      //   event:auditCancel,
      //   show: true,
      //   ifRender(row) {
      //     return (
      //       row.status === 2 ||
      //       row.status === "part_export" ||
      //       row.status === "part_turn"
      //     )
      //   }
      // },
      {
        label: '批准',
        event: audit,
        show: proxy.$permission('useAudit:audit'),
        ifRender(row) {
          return row.status === 2
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('useAudit:reject'),
        ifRender(row) {
          return (
            row.status === 2 ||
            (row.status === 4 && row.isCargoSpaceManage != 1)
          ) //待审核
        },
      },
      {
        label: '中止',
        event: stopRow,
        show: proxy.$permission('useAudit:stop'),
        ifRender(row) {
          return row.status === 4 || row.status === 7
        },
      },
    ],
  },
})
const selectRows = ref([])
const detailInfo = ref({
  visible: false,
  title: '',
  tableRow: {},
  id: '',
})
const exportInfo = ref({
  visible: false,
  title: '领用单出库',
  id: '',
})
const downShelfTaskInfo = ref({
  visible: false,
  title: '领用单出库',
  id: '',
})
const purchOrderIndfo = ref({
  visible: false,
  tableRow: {},
})
const applicationOrderInfo = ref({
  visible: false,
  tableRow: {},
})
const purchOrderDetailInfo = ref({
  visible: false,
  purchOrderId: '',
})
const applicationOrderDetailsInfo = ref({
  visible: false,
  title: '申购单明细',
  data: {},
})
const modifyInfo = ref({
  visible: false,
  title: '',
  returnStoreId: '',
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
const canAudit = computed(() => {
  return (
    selectRows.value.filter((item) => item.status !== 2).length === 0 &&
    selectRows.value.length > 0
  )
})
const canPurch = computed(() => {
  return (
    selectRows.value.filter(
      (item) =>
        item.status == 2 ||
        item.status == 'part_export' ||
        item.status == 'part_turn'
    ).length !== 0 && selectRows.value.length === 1
  )
})
const canCancel = computed(() => {
  return (
    selectRows.value.filter(
      (item) => item.status == 'part_export' || item.status == 'part_turn'
    ).length !== 0 && selectRows.value.length === 1
  )
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'useAudit' && el.url === val.url) {
                detailInfo.value.visible = false
                modifyInfo.value.visible = false
                advancedSearchInfo.value.visible = false
                preferenceInfo.value.visible = false
                detailListInfo.value.visible = false
                exportInfo.value.visible = false
                purchOrderIndfo.value.visible = false
                applicationOrderInfo.value.visible = false
                purchOrderDetailInfo.value.visible = false
                applicationOrderDetailsInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.value.visible = true
                  detailInfo.value.id = val.businessId
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    { deep: true, immediate: true }
  )
})
onDeactivated(() => {
  stopWatch()
})

async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = []
  let authStr = proxy.$store.state.permission.systemConfig.use_application_audit_auth_type
  let wayStr = proxy.$store.state.permission.systemConfig.use_application_audit_way
  if (authStr == 1 && wayStr == 1) {
    arr = onlyStoreDeptQueryArr
  }else if(authStr == 1 && wayStr == 2){
    arr = onlyExportDeptQueryArr
  }else if(authStr == 2 && wayStr == 1){
    arr = onlyStoreDepotQueryArr
  }else if(authStr == 2 && wayStr == 2){
    arr = onlyExportDepotQueryArr
  }
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}

// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.tableRow = row
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
//采购单明细
function showPurchOrderDetail(id, row) {
  sessionStorage.setItem('storeRowId', row.id)
  purchOrderDetailInfo.value.purchOrderId = id
  purchOrderDetailInfo.value.visible = true
}
//申购单明细
function showApplicationOrderDetail(id, row) {
  sessionStorage.setItem('storeRowId', row.id)
  applicationOrderDetailsInfo.value.data = { id: id }
  applicationOrderDetailsInfo.value.visible = true
}
// 出库
function _export(row) {
  sessionStorage.setItem('storeRowId', row.id)
  exportInfo.value.visible = true
  exportInfo.value.id = row.id
}
// 拣货
function downShelfTask(row) {
  //校验能否拣货
  validateDownShelf(row.id).then((resp) => {
    if (resp && resp.success) {
      sessionStorage.setItem('storeRowId', row.id)
      downShelfTaskInfo.value.visible = true
      downShelfTaskInfo.value.id = row.id
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      selectRows.value = data
      break
  }
}
function auditPurch(row) {
  //转采购
  purchOrderIndfo.value.visible = true
  if (row && row.id) {
    purchOrderIndfo.value.tableRow = row
  } else if (selectRows.value.length) {
    purchOrderIndfo.value.tableRow = selectRows.value[0]
  }
}
function auditApplication(row) {
  //转申购
  applicationOrderInfo.value.visible = true
  if (row && row.id) {
    applicationOrderInfo.value.tableRow = row
  } else if (selectRows.value.length) {
    applicationOrderInfo.value.tableRow = selectRows.value[0]
  }
}
function auditCancel(row = undefined) {
  //取消
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else if (selectRows.value.length) {
    ids = [selectRows.value[0].id]
  }
  applicationsCancel(ids).then((resp) => {
    if (resp && resp.success) {
      selectRows.value = []
      getList()
    }
  })
}
//批准
function audit(row = undefined) {
  const ids = getIds(row)
  validateDepotHighLevel(ids).then((res) => {
    if (res && res.success) {
      auditUseApplication(ids).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    }
  })
}
//驳回，其实和撤回是同样的效果
function reject(row = undefined) {
  proxy
    .$prompt('驳回理由', '领用审核', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[\S]+/,
      inputErrorMessage: '请输入驳回理由',
    })
    .then(({ value }) => {
      let param = {}
      param.ids = [row.id]
      param.remark = value
      rejectUseApplication(param).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}
//关闭，关闭时校验领用出库是否有待出库状态的，有不能关闭
function stopRow(row = undefined) {
  proxy
    .$confirm('中止后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      const ids = getIds(row)
      stopUseApplication(ids).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = selectRows.value.map((row) => row.id)
  }
  return ids
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'useApplicationOrderRatifyIndex-com.slip.spd.entity.vo.use.UseApplicationOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      //默认仓库
      let queryMap = {}
      let authStr = proxy.$store.state.permission.systemConfig.use_application_audit_auth_type
      let wayStr = proxy.$store.state.permission.systemConfig.use_application_audit_way
      if (authStr == 1 && wayStr == 1) {
        queryMap = onlyStoreDeptQueryMap
      }else if(authStr == 1 && wayStr == 2){
        queryMap = onlyExportDeptQueryMap
      }else if(authStr == 2 && wayStr == 1){
        queryMap = onlyStoreDepotQueryMap
      }else if(authStr == 2 && wayStr == 2){
        queryMap = onlyExportDepotQueryMap
      }
      filterInfo.value.query.queryMap = {
        ...queryMap,
        ...searchInfo.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getUseApplicationCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

let onlyStoreDeptQueryArr = [
  {
    asTbName: 'use_application_order',
    columnName: 'dept_id',
    queryType: 'IN',
    queryCategory: 'AND',
    value: 'multDeptAuth',
  }
]
let onlyExportDeptQueryArr = [
  {
    asTbName: 'use_application_order',
    columnName: 'export_dept_id',
    queryType: 'IN',
    queryCategory: 'AND',
    value: 'multDeptAuth',
  },
  {
    asTbName: 'use_application_order',
    columnName: 'dept_rule_ids',
    queryType: 'IN',
    queryCategory: 'AND',
    value: 'multDeptAuth',
  },
]
let onlyStoreDepotQueryArr = [
  {
    asTbName: 'use_application_order',
    columnName: 'depot_id',
    queryType: 'IN',
    queryCategory: 'AND',
    value: 'multDepotAuth',
  }
]
let onlyExportDepotQueryArr = [
  {
    asTbName: 'use_application_order',
    columnName: 'export_depot_id',
    queryType: 'IN',
    queryCategory: 'AND',
    value: 'multDepotAuth',
  },
  {
    asTbName: 'use_application_order',
    columnName: 'depot_rule_ids',
    queryType: 'IN',
    queryCategory: 'AND',
    value: 'multDepotAuth',
  },
]

let onlyStoreDeptQueryMap =  {
  deptAuth: {
    asTbName: 'use_application_order',
    columnName: 'dept_id',
    queryType: 'IN',
    queryCategory: 'OR',
    value: 'multDeptAuth',
  }
}
let onlyExportDeptQueryMap =  {
  exportDeptAuth: {
    asTbName: 'use_application_order',
    columnName: 'export_dept_id',
    queryType: 'IN',
    queryCategory: 'OR',
    value: 'multDeptAuth',
  },
  deptRuleIdsDeptAuth: {
    asTbName: 'use_application_order',
    columnName: 'dept_rule_ids',
    queryType: 'IN',
    queryCategory: 'OR',
    value: 'multDeptAuth',
  },
}
let onlyStoreDepotQueryMap = {
  depotAuth: {
    asTbName: 'use_application_order',
    columnName: 'depot_id',
    queryType: 'IN',
    queryCategory: 'OR',
    value: 'multDepotAuth',
  }
}
let onlyExportDepotQueryMap = {
  exportDepotAuth: {
    asTbName: 'use_application_order',
    columnName: 'export_depot_id',
    queryType: 'IN',
    queryCategory: 'OR',
    value: 'multDepotAuth',
  },
  deptRuleIdsDepotAuth: {
    asTbName: 'use_application_order',
    columnName: 'depot_rule_ids',
    queryType: 'IN',
    queryCategory: 'OR',
    value: 'multDepotAuth',
  },
}


let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'use_audit_status',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped>
.display-flex {
  padding-bottom: 10px;
}
</style>
